﻿Imports System.Web.Mvc
Imports System.Web.Mvc.Ajax

Namespace Utilitys
    Partial Public NotInheritable Class HelperExtensions

        Public Shared Function RawActionLink(ajaxHelper As AjaxHelper, linkText As String, actionName As String, controllerName As String, routeValues As Object, ajaxOptions As AjaxOptions, htmlAttributes As Object) As MvcHtmlString
            Dim repID = Guid.NewGuid().ToString()
            Dim lnk = ajaxHelper.ActionLink(repID, actionName, controllerName, routeValues, ajaxOptions, htmlAttributes)
            Return MvcHtmlString.Create(lnk.ToString().Replace(repID, linkText))
        End Function

        Public Shared Function GroupDropList(helper As HtmlHelper, name As String, data As IEnumerable(Of GroupListItem), SelectedValue As String, htmlAttributes As Object) As MvcHtmlString
            If data Is Nothing AndAlso helper.ViewData IsNot Nothing Then
                data = TryCast(helper.ViewData.Eval(name), IEnumerable(Of GroupListItem))
            End If
            If data Is Nothing Then
                Return Nothing
            End If

            Dim [select] = New TagBuilder("select")

            If htmlAttributes IsNot Nothing Then
                [select].MergeAttributes(New RouteValueDictionary(htmlAttributes))
            End If

            [select].GenerateId(name)

            Dim optgroupHtml = New StringBuilder()
            Dim groups = data.ToList()
            For Each group In data
                Dim groupTag = New TagBuilder("optgroup")
                groupTag.Attributes.Add("label", helper.Encode(group.Nombre))
                Dim optHtml = New StringBuilder()
                For Each item In group.Items
                    Dim [option] = New TagBuilder("option")
                    [option].Attributes.Add("value", helper.Encode(item.Value))
                    If SelectedValue IsNot Nothing AndAlso item.Value = SelectedValue Then
                        [option].Attributes.Add("selected", "selected")
                    End If
                    [option].InnerHtml = helper.Encode(item.Text)
                    optHtml.AppendLine([option].ToString(TagRenderMode.Normal))
                Next
                groupTag.InnerHtml = optHtml.ToString()
                optgroupHtml.AppendLine(groupTag.ToString(TagRenderMode.Normal))
            Next
            [select].InnerHtml = optgroupHtml.ToString()
            Return MvcHtmlString.Create([select].ToString(TagRenderMode.Normal))
            'Return [select].ToString(TagRenderMode.Normal)
        End Function



    End Class
End Namespace